<script lang="ts" setup>
import { ref, onMounted } from 'vue';
import { Page } from '@vben/common-ui';
import { columns, searchFormSchema } from './data';
import {
  getExceptionLogsApi,
  getRecentExceptionLogsApi,
  cleanExceptionLogsByDaysApi,
  batchDeleteExceptionLogsApi,
  exportExceptionLogsApi,
  type LogApi
} from '#/api/core/log';
import { ElMessage, ElMessageBox, ElButton, ElDialog, ElForm, ElFormItem, ElInputNumber, ElDivider } from 'element-plus';
import { $t } from '#/locales';
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import ExceptionDetail from './exception-detail.vue';
import ExceptionStats from './components/exception-stats.vue';

// 清理日志对话框
const cleanDialogVisible = ref(false);
const cleanForm = ref({
  days: 30,
});

// 详情对话框
const detailVisible = ref(false);
const currentId = ref('');

// 统计视图
const showStats = ref(true);

// 查看详情
async function handleView(record: LogApi.ExceptionLogDto) {
  currentId.value = record.id;
  detailVisible.value = true;
}

// 删除日志
async function handleDelete(record: LogApi.ExceptionLogDto) {
  try {
    await ElMessageBox.confirm(
      $t('system.exceptionLog.deleteConfirm'),
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    await batchDeleteExceptionLogsApi([record.id]);
    ElMessage.success($t('system.exceptionLog.deleteSuccess', { count: 1 }));
    gridApi.reload();
  } catch (error) {
    if (error instanceof Error) {
      ElMessage.error(error.message);
    }
  }
}

// 表格实例
const [Grid, gridApi] = useVbenVxeGrid({
  tableTitle: $t('system.exceptionLog.list'),
  gridOptions: {
    columns: [
      ...columns,
      {
        title: $t('system.role.operation'),
        width: 150,
        cellRender: {
          name: 'CellOperation',
          attrs: {
            onClick: ({ code, row }: { code: string; row: LogApi.ExceptionLogDto }) => {
              if (code === 'view') {
                handleView(row);
              } else if (code === 'delete') {
                handleDelete(row);
              }
            }
          },
          options: [
            {
              code: 'view',
              text: '查看详情',
              type: 'primary'
            },
            {
              code: 'delete',
              text: '删除',
              type: 'danger'
            }
          ]
        }
      }
    ],
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    proxyConfig: {
      autoLoad: true,  // 确保自动加载
      ajax: {
        query: async ({ page }: { page: { currentPage?: number; pageSize?: number } }) => {
          try {
            // 获取表单值
            const formValues = await gridApi.formApi.getValues();

            // 处理时间范围
            let startTime: string | undefined, endTime: string | undefined;
            if (formValues.timeRange && Array.isArray(formValues.timeRange) && formValues.timeRange.length === 2) {
              [startTime, endTime] = formValues.timeRange;
              delete formValues.timeRange;
            }

            // 组装请求参数
            const params: LogApi.ExceptionLogPagedRequest = {
              pageIndex: page.currentPage || 1,
              pageSize: page.pageSize || 10,
              startTime,
              endTime,
              ...formValues
            };

            // 执行请求
            const response = await getExceptionLogsApi(params);

            // 调试查看响应格式
            console.log('API response:', response);

            // API返回的是PagedList<T>类型，直接返回即可
            // vxe-table的adapter已经配置了识别items和totalCount的映射关系
            return response;
          } catch (error) {
            console.error('加载异常日志失败:', error);
            ElMessage.error('加载异常日志失败');
            return {
              items: [],
              totalCount: 0
            };
          }
        }
      }
    },
    toolbarConfig: {
      refresh: true,
      zoom: true,
      custom: true
    },
    // 启用分页
    pagerConfig: {
      enabled: true,
      pageSize: 10,
      pageSizes: [10, 20, 50, 100]
    }
  },
  formOptions: {
    schema: searchFormSchema,
    layout: 'horizontal',
    wrapperClass: 'grid-cols-4 2xl:grid-cols-4 xl:grid-cols-3 lg:grid-cols-3 md:grid-cols-2 sm:grid-cols-1',
    commonConfig: {
      componentProps: {
        class: 'w-full',
      }
    },
  },
  showSearchForm: true,
});

// 获取最近异常
const handleGetRecent = async () => {
  try {
    await getRecentExceptionLogsApi();
    gridApi.reload();
    ElMessage.success('获取最近异常成功');
  } catch (error) {
    ElMessage.error('获取最近异常失败');
  }
};

// 导出日志
const handleExport = async () => {
  try {
    // 获取表单值
    const formValues = await gridApi.formApi.getValues();

    // 处理时间范围
    let startTime, endTime;
    if (formValues.timeRange && Array.isArray(formValues.timeRange) && formValues.timeRange.length === 2) {
      [startTime, endTime] = formValues.timeRange;
      delete formValues.timeRange;
    }

    // 组装请求参数
    const params: LogApi.ExceptionLogPagedRequest = {
      pageIndex: 1,
      pageSize: 1000,
      startTime,
      endTime,
      ...formValues
    };

    const response = await exportExceptionLogsApi(params);
    const blob = new Blob([response], { type: 'text/csv' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = `exception_logs_${new Date().getTime()}.csv`;
    link.click();
    window.URL.revokeObjectURL(url);
  } catch (error) {
    ElMessage.error('导出失败');
  }
};

// 清理日志
const handleClean = async () => {
  try {
    await ElMessageBox.confirm(
      $t('system.exceptionLog.cleanConfirm'),
      $t('common.warning'),
      {
        confirmButtonText: $t('common.confirm'),
        cancelButtonText: $t('common.cancel'),
        type: 'warning',
      }
    );

    await cleanExceptionLogsByDaysApi(cleanForm.value.days);
    gridApi.reload();
    cleanDialogVisible.value = false;
  } catch (error) {
    console.error('清理日志失败:', error);
  }
};

onMounted(() => {
  // 确保组件挂载后触发数据加载
  console.log('组件已挂载，即将加载数据');
  setTimeout(() => {
    gridApi.reload();
  }, 100);
});
</script>

<template>
  <Page>
    <!-- 统计视图 -->
    <div v-if="showStats">
      <ExceptionStats />
    </div>

    <Grid>
      <template #toolbar-prefix>
        <ElButton
          :type="showStats ? 'success' : 'default'"
          @click="showStats = !showStats"
          size="small"
          title="显示/隐藏统计图表"
        >
          <i class="icon-emoji">&#x1F4CA;</i>{{ showStats ? '隐藏统计' : '显示统计' }}
        </ElButton>
        <ElDivider direction="vertical" />
      </template>

      <template #toolbar-tools>
        <ElButton type="success" @click="handleGetRecent" size="small">
          <i class="icon-emoji">&#x21BB;</i>最近异常
        </ElButton>
        <ElButton type="primary" @click="handleExport" size="small">
          <i class="icon-emoji">&#11015;</i>导出日志
        </ElButton>
        <ElButton type="danger" @click="cleanDialogVisible = true" size="small">
          <i class="icon-emoji">&#x1F5D1;</i>清理日志
        </ElButton>
      </template>
    </Grid>

    <!-- 清理日志对话框 -->
    <ElDialog v-model="cleanDialogVisible" title="清理日志" width="400px">
      <ElForm :model="cleanForm" label-width="100px">
        <ElFormItem label="保留天数">
          <ElInputNumber v-model="cleanForm.days" :min="0" :max="365" />
        </ElFormItem>
      </ElForm>
      <template #footer>
        <ElButton @click="cleanDialogVisible = false">取消</ElButton>
        <ElButton type="primary" @click="handleClean">确定</ElButton>
      </template>
    </ElDialog>

    <!-- 异常详情对话框 -->
    <ExceptionDetail
      v-model:visible="detailVisible"
      :id="currentId"
    />
  </Page>
</template>

<style lang="scss" scoped>
:deep(.vben-form) {
  display: grid;
  gap: 16px;
  padding: 16px;

  .el-form-item {
    margin-bottom: 0;
  }

  // 确保所有表单控件充分利用可用宽度
  .el-date-editor.el-input__wrapper,
  .el-input__wrapper,
  .el-select {
    width: 100%;
  }

  // 确保日期时间选择器有足够的宽度
  .el-date-editor--datetimerange {
    min-width: 360px;
  }
}

// 按钮图标样式
:deep(.el-button) {
  .icon-emoji {
    margin-right: 4px;
    font-style: normal;
  }
}

// 表格操作列样式优化
:deep(.vxe-cell--operate) {
  .el-button {
    margin-left: 0;
    margin-right: 8px;

    &:last-child {
      margin-right: 0;
    }
  }
}
</style>
